package com.jvm.d1;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * 描述:
 *
 * @author luzhongfu
 * Created by lucky on 2019-10-11 2:04 PM
 */
public class Foo {

    private boolean flag;

    public boolean getFlag() {
        return flag;
    }
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Unsafe unsafe = getUnsafe();
        Foo foo = new Foo();
        Field field = foo.getClass().getDeclaredField("flag");
        long offset = unsafe.objectFieldOffset(field);
        unsafe.putInt(foo, offset, 2);
        if (foo.getFlag()) System.out.println("Hello,Java");
        if (foo.getFlag() == true) System.out.println("Hello, JVM");
    }

    public static Unsafe getUnsafe() throws NoSuchFieldException, IllegalAccessException {
        Field f = Unsafe.class.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        return (Unsafe) f.get(null);
    }
}
